<template>
  <div>
    <div>
      <div class="row-spaceb mg20">
        <p class="fwbold fs-md">· 我的服务产品</p>
        <el-button
          icon="el-icon-plus"
          type="primary"
          plain
          size="small"
          @click="supplyForList"
        >申请上架</el-button>
      </div>
      <el-divider></el-divider>
      <el-form
        :inline="true"
        :model="searchForm"
        style="padding: 10px 30px 0 30px"
      >
        <el-form-item label="产品编码">
          <el-input
            v-model="searchForm.productId"
            clearable
            placeholder="请输入产品编码"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.productName"
            clearable
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            @click="search"
          >查询</el-button>
        </el-form-item>
      </el-form>
      <div class="card">
        <el-tabs
          v-model="activeName"
          @tab-click="tabClick"
          type="border-card"
          class="ml30 mr30 mb30"
        >
          <el-tab-pane
            :label="item.dictLabel"
            :name="item.dictValue"
            v-for="(item, index) in productApplyStatus"
            :key="index"
          >
            <el-table
              v-loading="tableLoading"
              :data="tableList"
              style="width: 100%"
            >
              <el-table-column
                prop="productId"
                label="产品编号"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="productName"
                label="服务产品名称"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="productTypeName"
                label="服务类型"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="companyName"
                label="服务商"
                width="150"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="upperPrice"
                label="服务产品价格(元)"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.pricingType === 1 ? $priceFormat(scope.row.limitOriginalPrice,scope.row.upperOriginalPrice) : '面议' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="quotaPrice"
                label="拟补贴金额(元)"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  {{scope.row.pricingType === 1 ? $priceFormat(scope.row.limitDiscount,scope.row.upperDiscount) : '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="transNum"
                label="成交笔数"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.transNum || 0}}
                </template>
              </el-table-column>
              <el-table-column
                prop="auditStatus"
                label="审核状态"
              >
                <template slot-scope="scope">
                  <span
                    v-if="scope.row.auditStatus == -1"
                    class="color-red"
                  >未提交</span>
                  <span
                    v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 7 || scope.row.auditStatus == 6"
                    class="color-warning"
                  >待审核</span>
                  <span
                    v-if="scope.row.auditStatus == 1"
                    class="color-success"
                  >审核通过</span>
                  <div
                    v-else-if="scope.row.auditStatus == 2"
                    class="status-wrapper"
                  >
                    <span class="color-red">退回修改</span>
                    <el-tooltip
                      :content="scope.row.comment"
                      placement="top"
                    >
                      <p class="feedback-text">{{scope.row.comment}}</p>
                    </el-tooltip>
                  </div>
                  <div
                    v-else-if="scope.row.auditStatus == 3"
                    class="status-wrapper"
                  >
                    <span class="color-red">审核不通过</span>
                    <el-tooltip
                      :content="scope.row.comment"
                      placement="top"
                    >
                      <p class="feedback-text">{{scope.row.comment}}</p>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="产品状态">
                <template slot-scope="scope">
                  <span
                    v-if="scope.row.listStatus == 0"
                    class="color-warning"
                  >未上架</span>
                  <span
                    v-if="scope.row.listStatus == 1"
                    class="color-success"
                  >已上架</span>
                  <span
                    v-if="scope.row.listStatus == 2"
                    class="color-red"
                  >下架</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                fixed="right"
                width="120px"
              >
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.auditStatus != -1"
                    type="text"
                    @click="btnClick(scope.row, scope.$index, 'view')"
                  >预览</el-button>
                  <el-button
                    v-if="scope.row.auditStatus == -1 || scope.row.listStatus == 2 || scope.row.auditStatus == 2"
                    type="text"
                    class="ml10"
                    @click="btnClick(scope.row, scope.$index, 'edit')"
                  >
                    编辑
                  </el-button>
                  <el-button
                    v-if="scope.row.auditStatus == 0"
                    type="text"
                    class="ml10"
                    @click="btnClick(scope.row, scope.$index, 'revoke')"
                  >
                    撤回
                  </el-button>
                  <el-button
                    v-if="(scope.row.listStatus == 0 && scope.row.auditStatus == 1) || (scope.row.listStatus == 2 && scope.row.auditStatus == 1)"
                    type="text"
                    class="ml10"
                    @click="btnClick(scope.row, scope.$index, 'ground')"
                  >
                    上架
                  </el-button>
                  <el-button
                    v-if="scope.row.listStatus == 1"
                    type="text"
                    class="ml10"
                    @click="btnClick(scope.row,scope.$index, 'ground')"
                  >下架
                  </el-button>
                  <el-button
                    v-if="scope.row.listStatus == 1"
                    type="text"
                    class="ml10"
                    @click="openPriceDialog(scope.row)"
                  >修改价格</el-button>
                  <el-button
                    type="text"
                    class="ml10"
                    v-if="scope.row.listStatus == 0 && scope.row.auditStatus == -1"
                    @click="btnClick(scope.row, scope.$index, 'delete')"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="row-end mt15">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageData.currentPage"
                :page-sizes="[10, 20, 30, 40, 50]"
                :page-size="pageData.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageData.totalPage"
              >
              </el-pagination>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <el-dialog
      title="申请上架"
      width="30%"
      :visible="supplyDialogVisible"
    >
      <span>请先补充"服务商信息"才可进行"服务商品上架申请"</span>
      <div
        class="row-center"
        slot="footer"
      >
        <el-button
          @click="supplyDialogVisible=false"
          type="danger"
          plain
        >暂不申请</el-button>
        <el-button
          style="margin-left: 40px;"
          type="danger"
          @click="goToEditInfo"
        >去填写</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="修改价格"
      :visible.sync="showPriceDialog"
      width="1000px"
    >
      <el-form
        :model="priceForm"
        ref="priceForm"
        label-width="160px"
        :rules="priceRules"
      >
        <el-form-item label="产品名称">
          <el-input
            v-model="priceForm.productName"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="产品类型">
          <el-input
            v-model="priceForm.productTypeName"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="核准价格(元)">
          <el-input
            v-model="priceForm.approvedPrice"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="平台销售价格(元)"
          prop="platformPrice"
        >
          <el-input
            v-model.number="priceForm.platformPrice"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="市场指导价(元)"
          prop="marketPrice"
        >
          <el-input
            v-model.number="priceForm.marketPrice"
            type="number"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="fs14 color-warning"><i class="el-icon-warning"></i> 在不扩大财政补贴总额的前提下可自主调整价格。通用券补贴不超过合同金额的80%（诊断类最高1万元）或50%（其他类最高3万元）</div>
      <div class="fs14 color-red mt5"><i class="el-icon-warning"></i>调整限制：企业诊断类产品核准价格12500元以下、其他类核准价格60000元以下的，平台销售价格不能大于核准价</div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="showPriceDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="isSubmitting"
          @click="submitPriceForm"
        >提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getProductOwnPage,
  productGround,
  productRevoke,
  productDelete,
  updateProductPrice,
} from "@/api/homeApi";
import { mapGetters } from "vuex";
export default {
  components: {},
  data() {
    return {
      isHaveInfo: true,
      tableLoading: false,
      listData: [],
      activeName: "all",
      productApplyStatus: [
        { dictLabel: "全部", dictValue: "all" },
        { dictLabel: "待审核", dictValue: "0" },
        { dictLabel: "审核通过", dictValue: "1" },
        { dictLabel: "退回修改", dictValue: "2" },
        { dictLabel: "审核不通过", dictValue: "3" },
        { dictLabel: "已上架", dictValue: "4" },
        { dictLabel: "已下架", dictValue: "5" },
      ],
      pageData: {
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,
      },
      tableList: [],
      supplyDialogVisible: false,
      showPriceDialog: false,
      priceForm: {
        productId: "",
        productName: "",
        platformPrice: 0,
        marketPrice: 0,
      },
      priceRules: {
        platformPrice: [
          { required: true, message: "请输入平台销售价格", trigger: "blur" },
          { validator: this.validatePrice, trigger: "blur" },
        ],
        marketPrice: [
          { required: true, message: "请输入市场指导价", trigger: "blur" },
        ],
      },
      isSubmitting: false,
      searchForm: {
        productId: "",
        productName: "",
      },
    };
  },
  computed: {
    commonDict() {
      return this.$store.state.common.commonDict;
    },
    ...mapGetters(["userInfo"]),
  },
  mounted() {
    this.getTableList();
  },
  methods: {
    // 申请上架
    supplyForList() {
      if (this.userInfo.isServiceInfoComplete) {
        this.$router.push({ name: "服务产品上架" });
      } else {
        this.supplyDialogVisible = true;
      }
    },
    // 去填写
    goToEditInfo() {
      this.supplyDialogVisible = false;
      this.$router.push({ name: "服务商信息" });
    },
    tabClick(val) {
      if (val.name === "all") {
        this.getTableList();
      } else if (val.name === "0") {
        this.getTableList(0);
      } else if (val.name === "1") {
        this.getTableList(1);
      } else if (val.name === "2") {
        this.getTableList(2);
      } else if (val.name === "3") {
        this.getTableList(3);
      } else if (val.name === "4") {
        this.getTableList("", 1);
      } else if (val.name === "5") {
        this.getTableList("", 2);
      }
    },
    handleSizeChange(val) {
      this.$set(this.pageData, "pageSize", val);
      this.getTableList();
    },
    handleCurrentChange(val) {
      this.$set(this.pageData, "currentPage", val);
      this.getTableList();
    },
    search() {
      this.$set(this.pageData, "currentPage", 1);
      this.getTableList();
    },
    getTableList(auditStatus = "", listStatus = "") {
      this.tableLoading = true;
      getProductOwnPage({
        pageNo: this.pageData.currentPage,
        pageNum: this.pageData.pageSize,
        auditStatus,
        listStatus,
        ...this.searchForm,
      })
        .then((res) => {
          if (res.code === 200) {
            this.tableList = [...res.rows];
            this.pageData.totalPage = res.total;
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    btnClick(row, index, type) {
      let self = this;
      switch (type) {
        case "view":
          self.$router.push(
            `serviceProductPreview?id=${row.productId}&status=${row.listStatus}`
          );
          break;
        case "ground":
          let listStatus = 0;
          self.tableLoading = true;
          if (row.listStatus == 0 || row.listStatus == 2) {
            // 未上架、下架进行上架操作
            listStatus = 1;
            self.handleGroundOperation(row, listStatus);
          } else if (row.listStatus == 1) {
            // 上架进行下架操作
            listStatus = 2;
            // 上架进行下架操作，添加确认提示
            self
              .$confirm(
                "下架后需要通过下一批次服务产品审核才能重新上架，确认是否下架？（本批需要调整的产品下架后优先审核）",
                "温馨提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              )
              .then(() => {
                listStatus = 2;
                self.handleGroundOperation(row, listStatus);
              })
              .catch(() => {
                 self.tableLoading = false
              });
          }
          break;
        case "edit":
          self.$router.push(`serviceProductList?id=${row.productId}&from=2`);
          break;
        case "revoke":
          this.$confirm("是否撤回此条数据?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              productRevoke({ productId: row.productId })
                .then((res) => {
                  if (res.code === 200) {
                    self.$message.success("操作成功!");
                    self.getTableList();
                  } else {
                    self.$message.error(res.msg);
                  }
                })
                .finally(() => {
                  self.tableLoading = false;
                });
            })
            .catch(() => {});
          break;
        case "delete":
          this.$confirm("是否删除此条数据?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              productDelete({ productId: row.productId })
                .then((res) => {
                  if (res.code === 200) {
                    self.$message.success("操作成功!");
                    self.getTableList();
                  } else {
                    self.$message.error(res.msg);
                  }
                })
                .finally(() => {
                  self.tableLoading = false;
                });
            })
            .catch(() => {});
          break;
        default:
          break;
      }
    },
    // 新增处理上下架操作的方法
    handleGroundOperation(row, listStatus) {
      this.tableLoading = true;
      productGround({
        listStatus,
        productId: row.productId,
      })
        .then((res) => {
          if (res.code === 200) {
            this.$message.success(listStatus === 1 ? "上架成功!" : "下架成功!");
            this.getTableList();
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    openPriceDialog(row) {
      this.priceForm = {
        productId: row.productId,
        productName: row.productName,
        platformPrice: row.upperOriginalPrice / 100, // 转换为元
        marketPrice: row.upperMarketGuidancePrice / 100, // 转换为元
        productTypeId: row.productTypeId,
        approvedPrice:row.approvedPrice / 100,
        productTypeName:row.productTypeName
      };
      this.showPriceDialog = true;
    },
    validatePrice(rule, value, callback) {
      if (value > this.priceForm.marketPrice) {
        callback(new Error("平台销售价格不能大于市场指导价"));
      } else {
        callback();
      }
    },
    submitPriceForm() {
      this.$refs.priceForm.validate((valid) => {
        if (valid) {
          console.log(this.priceForm);
          this.submitData()
          // if (
          //   [134, 137, 138, 139, 140].includes(this.priceForm.productTypeId)
          // ) {
          //   if (this.priceForm.platformPrice < this.priceForm.approvedPrice) {
          //      this.submitData()
          //   } else {
          //     this.$message.warning("平台销售价格不能高于核准价格时");
          //   }
          // }
        }
      });
    },
    submitData() {
      this.isSubmitting = true;
      const payload = {
        productId: this.priceForm.productId,
        upperOriginalPrice: this.priceForm.platformPrice * 100,
        limitOriginalPrice: this.priceForm.platformPrice * 100,
        upperMarketGuidancePrice: this.priceForm.marketPrice * 100,
        limitMarketGuidancePrice: this.priceForm.marketPrice * 100,
      };
      updateProductPrice(payload)
        .then((response) => {
          if (response.code === 200) {
            this.$message.success("价格修改成功");
            this.showPriceDialog = false;
            this.getTableList();
          } else {
            this.$message.error(response.msg || "价格修改失败");
          }
        })
        .catch((error) => {
          this.$message.error("请求失败，请稍后重试");
        })
        .finally(() => {
          this.isSubmitting = false;
        });
    },
  },
};
</script>

<style scoped>
p {
  margin: 0;
  padding: 0;
}
:deep .el-divider--horizontal {
  margin: 12px 0;
}
:deep .el-menu--horizontal > .el-menu-item.is-active {
  border-bottom-color: #d32521;
}
:deep .el-table thead {
  color: #000;
}
.status-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.feedback-text {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}
</style>
